package org.javaapps.demo.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.javaapps.common.util.URLHelper;
import org.javaapps.demo.common.Constants;
import org.javaapps.demo.model.UserModel;

public class LoginFilter implements Filter {

	private String notFilterDir = "";
	protected Log log = LogFactory.getLog(this.getClass());
	private FilterConfig filterConfig;

	public void destroy() {
		notFilterDir = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse res = (HttpServletResponse) response;
			String uri = req.getRequestURI();
			String realuri = URLHelper.requestRelayString(req);
			String[] notFilterDirs = notFilterDir.split(",");
			for (int i = 0; i < notFilterDirs.length; i++) {
				String notFilterDirValue = notFilterDirs[i];
				if (uri.indexOf(notFilterDirValue) != -1) {
					chain.doFilter(request, response);
					return;
				}
			}
			HttpSession session = req.getSession();
			UserModel user = (UserModel) session.getAttribute(Constants.SESSION_USER);
			if (user == null)
				res.sendRedirect(this.filterConfig.getServletContext().getContextPath() + Constants.USER_LOGIN_PAGE + "?returnUrl=" + realuri);
			else
				chain.doFilter(request, response);
		} catch (Exception e) {
			log.error(e);
		}
	}
	
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		notFilterDir = filterConfig.getInitParameter("notFilterDir");
	}

}
